package com.yyw.rabbitmq.core.serialize.conver;

import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * @author yiyw
 * @ClassName RabbitMessageConverterDecorator.java
 * @Description Message 装饰者模式，装饰 GenericMessageConverter.java
 * @createTime 2021年07月28日 23:47:00
 */
public class RabbitMessageConverterDecorator implements MessageConverter {

    private GenericMessageConverter genericMessageConverter;

    public RabbitMessageConverterDecorator(GenericMessageConverter genericMessageConverter) {
        Preconditions.checkNotNull(genericMessageConverter);
        this.genericMessageConverter = genericMessageConverter;
    }

    /**
     * 发送消息的时候，需要把我们的 Message 序列化为Byte[] 并且赋值到 amqp的Message中去
     *
     * @param o
     * @param messageProperties
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        // 装饰者模式，对Message进行装饰
        messageProperties.setExpiration(String.valueOf(60 * 60 * 1000 * 24));
        return genericMessageConverter.toMessage(o, messageProperties);
    }

    /**
     * 接收到消息后，需要将 amqp的Message中取出 body 转化为 我们自己的 Message
     *
     * @param message
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        return genericMessageConverter.fromMessage(message);
    }
}